﻿#region Copyright (c) 2013-04, Olaf Kober <amarok.projects@gmail.com>
//================================================================================
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//================================================================================
#endregion

#if TESTS

using System;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;


namespace Amarok.Agents
{
	[TestFixture]
	public class Test_InformationHandler
	{
		private class MyInformation : Information
		{
		}


		private Int32 AsyncHandlerCalled;
		private MyInformation AsyncHandlerMessage;
		private Boolean AsyncHandlerThrowBeforeAwait;
		private Boolean AsyncHandlerThrowAfterAwait;


		private async Task AsyncHandler(MyInformation message)
		{
			AsyncHandlerMessage = message;
			AsyncHandlerCalled++;

			if (AsyncHandlerThrowBeforeAwait)
				throw new ApplicationException("BEFORE");

			await Task.Factory.StartNew(() => Thread.Sleep(100));

			if (AsyncHandlerThrowAfterAwait)
				throw new ApplicationException("AFTER");
		}

		[SetUp]
		public void Setup()
		{
			AsyncHandlerCalled = 0;
			AsyncHandlerMessage = null;
			AsyncHandlerThrowBeforeAwait = false;
			AsyncHandlerThrowAfterAwait = false;

			DefaultDispatcherHooks.Reset();
		}


		// --- TESTS ---


		[Test]
		public void Test_Invoke()
		{
			MyInformation callbackMessage = null;
			Int32 callbackCalled = 0;

			var callback = new Action<MyInformation>(msg =>
				{
					callbackMessage = msg;
					callbackCalled++;
				});

			var handler = new InformationHandler<MyInformation>(callback);
			var handlerInterface = (IHandler)handler;

			Assert.That(handler.Callback, Is.SameAs(callback));
			Assert.That(handler.AsyncCallback, Is.Null);

			var message = new MyInformation();
			message.Label = "Invoke";
			handlerInterface.Invoke(message);

			Assert.That(callbackCalled, Is.EqualTo(1));
			Assert.That(callbackMessage, Is.SameAs(message));
		}

		[Test]
		public void Test_Invoke_Async()
		{
			var callback = new Func<MyInformation, Task>(AsyncHandler);
			var handler = new InformationHandler<MyInformation>(callback);
			var handlerInterface = (IHandler)handler;

			var signal = new AutoResetEvent(false);
			DefaultDispatcherHooks.InformationHandlerCompleted = msg =>
				{
					signal.Set();
				};

			Assert.That(handler.Callback, Is.Null);
			Assert.That(handler.AsyncCallback, Is.SameAs(callback));

			var message = new MyInformation();
			message.Label = "Invoke_Async";
			handlerInterface.Invoke(message);

			signal.WaitOne(5000);

			Assert.That(AsyncHandlerCalled, Is.EqualTo(1));
			Assert.That(AsyncHandlerMessage, Is.SameAs(message));
		}

		[Test]
		public void Test_Invoke_Exception()
		{
			MyInformation callbackMessage = null;
			Int32 callbackCalled = 0;

			var callback = new Action<MyInformation>(msg =>
				{
					callbackMessage = msg;
					callbackCalled++;

					throw new ApplicationException("TEST");
				});

			Message hookMessage = null;
			Exception hookException = null;
			Int32 hookCalled = 0;

			DefaultDispatcherHooks.InformationHandlerFailed = (msg, e) =>
				{
					hookMessage = msg;
					hookException = e;
					hookCalled++;
				};

			var handler = new InformationHandler<MyInformation>(callback);
			var handlerInterface = (IHandler)handler;

			Assert.That(handler.Callback, Is.SameAs(callback));
			Assert.That(handler.AsyncCallback, Is.Null);

			var message = new MyInformation();
			handlerInterface.Invoke(message);

			Assert.That(callbackCalled, Is.EqualTo(1));
			Assert.That(callbackMessage, Is.SameAs(message));

			Assert.That(hookCalled, Is.EqualTo(1));
			Assert.That(hookMessage, Is.SameAs(message));
			Assert.That(hookException, Is.TypeOf<ApplicationException>());
			Assert.That(hookException.Message, Is.EqualTo("TEST"));
		}

		[Test]
		public void Test_Invoke_Exception_Async_BeforeAwait()
		{
			AsyncHandlerThrowBeforeAwait = true;

			Message hookMessage = null;
			Exception hookException = null;
			Int32 hookCalled = 0;
			var signal = new AutoResetEvent(false);

			DefaultDispatcherHooks.InformationHandlerFailed = (msg, e) =>
				{
					hookMessage = msg;
					hookException = e;
					hookCalled++;
				};
			DefaultDispatcherHooks.InformationHandlerCompleted = msg =>
				{
					signal.Set();
				};

			var callback = new Func<MyInformation, Task>(AsyncHandler);
			var handler = new InformationHandler<MyInformation>(callback);
			var handlerInterface = (IHandler)handler;

			Assert.That(handler.Callback, Is.Null);
			Assert.That(handler.AsyncCallback, Is.SameAs(callback));

			var message = new MyInformation();
			message.Label = "Invoke_Exception_Async_BeforeAwait";
			handlerInterface.Invoke(message);

			signal.WaitOne(5000);

			Assert.That(AsyncHandlerCalled, Is.EqualTo(1));
			Assert.That(AsyncHandlerMessage, Is.SameAs(message));

			Assert.That(hookCalled, Is.EqualTo(1));
			Assert.That(hookMessage, Is.SameAs(message));
			Assert.That(hookException, Is.TypeOf<ApplicationException>());
			Assert.That(hookException.Message, Is.EqualTo("BEFORE"));
		}

		[Test]
		public void Test_Invoke_Exception_Async_AfterAwait()
		{
			AsyncHandlerThrowAfterAwait = true;

			Message hookMessage = null;
			Exception hookException = null;
			Int32 hookCalled = 0;
			var signal = new AutoResetEvent(false);

			DefaultDispatcherHooks.InformationHandlerFailed = (msg, e) =>
				{
					hookMessage = msg;
					hookException = e;
					hookCalled++;
				};
			DefaultDispatcherHooks.InformationHandlerCompleted = msg =>
				{
					signal.Set();
				};

			var callback = new Func<MyInformation, Task>(AsyncHandler);
			var handler = new InformationHandler<MyInformation>(callback);
			var handlerInterface = (IHandler)handler;

			Assert.That(handler.Callback, Is.Null);
			Assert.That(handler.AsyncCallback, Is.SameAs(callback));

			var message = new MyInformation();
			message.Label = "Invoke_Exception_Async_AfterAwait";
			handlerInterface.Invoke(message);

			signal.WaitOne(5000);

			Assert.That(AsyncHandlerCalled, Is.EqualTo(1));
			Assert.That(AsyncHandlerMessage, Is.SameAs(message));

			Assert.That(hookException, Is.TypeOf<ApplicationException>());
			Assert.That(hookException.Message, Is.EqualTo("AFTER"));
			Assert.That(hookCalled, Is.EqualTo(1));
			Assert.That(hookMessage, Is.SameAs(message));
		}

		[Test]
		public void Test_Construction_NullAction()
		{
			Assert.Throws<ArgumentNullException>(() =>
				{
					var handler = new InformationHandler<MyInformation>((Action<MyInformation>)null);
				});
		}

		[Test]
		public void Test_Construction_Async_NullAction()
		{
			Assert.Throws<ArgumentNullException>(() =>
				{
					var handler = new InformationHandler<MyInformation>((Func<MyInformation, Task>)null);
				});
		}

	}
}

#endif
